package com.herench.bunch.clinic.convert;


import ca.uhn.hl7v2.model.GenericComposite;
import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.*;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.DataFormatUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Iterator;

public class QueryBalanceConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgInHos(ProxyMsgCodeConstant.QUERY_BALANCE);
        QBP_Q11 hl7 = (QBP_Q11) requestMessage.getHl7Message();
        GenericComposite gc = (GenericComposite) hl7.getQPD().getQpd3_UserParametersInsuccessivefields().getData();
        if (gc != null) {
            Varies varies = (Varies) gc.getComponent(1);
            if (varies != null) {
                GenericPrimitive primitive = (GenericPrimitive) varies.getData();
                String qpdString = primitive.getValue();
                String[] qpds = qpdString.split("#");
                if (qpds.length < 2) {
                    throw new RuntimeException("缺少必要参数");
                }
                for (String qpd : qpds) {
                    String[] temp = qpd.split("=");
                    if (temp.length>1){
                        String res = temp[1];
                        document.getRootElement().addElement(temp[0]).addText(temp[1] != null ? temp[1] : "");
                    }else {
                        document.getRootElement().addElement(temp[0]).addText("");
                    }
                }
            }
        }
        String res = document.asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = "+ res);
        return document;
    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        logger.info("200290 from HIS XML = "+ message);
        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);

        MSA msa = rtbK13.getMSA();
        msa.getErrorCondition().getCe1_Identifier().setValue(doc.getRootElement().elementTextTrim("IsSuccessed"));
        msa.getErrorCondition().getCe2_Text().setValue(doc.getRootElement().elementTextTrim("ErrorMsg"));


        RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();
        Element element = doc.getRootElement().element("Data");
        Element items = doc.getRootElement().element("Data").element("DepositList");

        StringBuffer str = new StringBuffer();
        str.append("TotalSpend=").append(element.elementTextTrim("TotalSpend")).append("#")
                .append("Balance=").append(element.elementTextTrim("Balance"));

        RDF rdf = rtbK13.getROW_DEFINITION().getRDF();
        rdf.getRdf1_NumberOfColumnsPerRow().setValue(str.toString());

        int index = 0;
        for (Iterator<Element> iterator = items.elementIterator(); iterator.hasNext(); ) {
            Element el = iterator.next();
            RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
            CE ce = new CE(rtbK13);
            ce.getCe1_Identifier().setValue("RD");
            StringBuffer buffer = new StringBuffer();
            buffer.append("PayTime=").append(el.elementTextTrim("PayTime")).append("#")
                    .append("PayType=").append(el.elementTextTrim("PayType")).append("#")
                    .append("PayMoney=").append(el.elementTextTrim("PayMoney")).append("#")
                    .append("ReceiptNum=").append(el.elementTextTrim("ReceiptNum"));
            ce.getCe2_Text().setValue(buffer.toString());
            rdt.getColumnValue().setData(ce);
            definition.insertRDT(rdt, index++);
        }
        return rtbK13;
    }

    @Override
    public Message generatorReqMessage() throws Exception {
        QBP_Q11 qbp = new QBP_Q11();
        qbp.initQuickstart("QBP_Q11", "QBP_Q11", "P");
        MSH msh = qbp.getMSH();
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200050");
        QPD qpd = qbp.getQPD();
        qpd.getMessageQueryName().getIdentifier().setValue("查询患者预约列表（B107）");
        qpd.getQpd2_QueryTag().setValue("QR");
        CE ce = new CE(qbp);

        QdbParamsHelper qdbParamsHelper = new QdbParamsHelper();
        qdbParamsHelper.addParams("HISPatientId","4002189111182870555" );
        qdbParamsHelper.addParams("IDCardNo","422202199310022411" );
        qdbParamsHelper.addParams("MedCardNo","" );
        qdbParamsHelper.addParams("CureCardNo","" );
        qdbParamsHelper.addParams("StartDate","2018-09-15" );
        qdbParamsHelper.addParams("EndDate","2018-09-15" );

        ce.getCe2_Text().setValue(qdbParamsHelper.toString());
        qpd.getQpd3_UserParametersInsuccessivefields().setData(ce);


        return qbp;
    }
}
